package com.fss.cart.service.impl;

import com.fss.cart.domain.*;
import com.fss.cart.mapper.CartMapper;

import com.fss.cart.service.CartService;

import com.fss.home.mapper.HomeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-26
 */
@Service
public class CartServiceImpl implements CartService
{
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private HomeMapper homeMapper;

    @Override
    public void add(List<CartItem> list, Long userId) {
        Long cartId=this.ensureCartExists(userId);
        //System.out.println("-----------"+cartId);
        for(CartItem item:list)
        {
            cartMapper.add(item.getSkuId(),cartId,item.getQuantity(),item.getProductId());
        }
    }


    @Override
    public List<CartProduct> getCartProductsByCartId(Long cartId) {
        return cartMapper.getCartProductsByCartId(cartId);
    }

    @Override
    public Stock getStockBySkuId(Long skuId) {
        return new Stock(cartMapper.getStockBySkuId(skuId));
    }

    @Override
    public void deleteCartItems(List<Long> ids) {
        cartMapper.deleteCartItems(ids);
    }

    @Override
    public void updateCartItem(Long id, Integer quantity) {
        cartMapper.updateCartItem(id, quantity);
    }

    public Long ensureCartExists(long userId) {
        Long cartId = cartMapper.getCartIdByUserId(userId);
        if (cartId == null) {
            cartMapper.createCart(userId);
            cartId = cartMapper.getCartIdByUserId(userId);
        }
        return cartId;
    }
}
